package com.pengpeng.dynamic.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切换处理器
 * @author 彭鹏
 * @date 2021/11/4.
 */
@Aspect
@Order(-1)  // 该切面应当先于 @Transactional 执行
@Component
@Slf4j
public class DynamicDataSourceAspect {

    @Before("@annotation(dataSource)")
    public void switchDataSource(JoinPoint point,DataSource dataSource){
        if(DynamicDataSourceContextHolder.containDataSourceKey(dataSource.value())){
            DynamicDataSourceContextHolder.setDataSourceKey(dataSource.value());
            log.info("Switch DataSource to [{}] in Method [{}]", DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature());
        }else {
            log.error("DataSource[{}] doesn't exist, use default DataSource",dataSource.value());
        }
    }

    @After("@annotation(dataSource)")
    public void restoreDataSource(JoinPoint point,DataSource dataSource){
        DynamicDataSourceContextHolder.clearDataSourceKey();
        log.info("Restore DataSource to {}in Method {}",DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature());
    }
}
